package com.meyou.javascript.rewriter;

public class RewriteIdGen {

	private static final int[] codes = new int[62];
	
	private String genPrefix;
	
	private String suffixCode;
	
	static {
		
		int idx = 0;
		
		for (int i = 97; i <= 122; i++) 
		{
			codes[idx++] = i;
		}
		
		for (int i = 65; i <= 90; i++) 
		{
			codes[idx++] = i;
		}
		
		for (int i = 48; i <= 57; i++)
		{
			codes[idx++] = i;
		}
		
	}
	
	public RewriteIdGen(String genPrefix)
	{
		super();
		
		this.genPrefix = genPrefix;
	}
	
	public String genId()
	{
		genSuffix();
		return genPrefix + suffixCode;
	}
	
	protected synchronized void genSuffix() {
		if (suffixCode == null)
		{
			suffixCode = Character.toString((char) codes[0]);
		} 
		else
		{
			char ch = suffixCode.charAt(suffixCode.length() - 1);
			if (Character.isDigit(ch)) 
			{
				int idx = 52 + ((int) ch - (int) '0');
				if (idx == 61) 
				{
					int jdx = suffixCode.length() - 2;
					if (jdx >= 0 && suffixCode.charAt(jdx) != '9')
					{
						if (Character.isDigit(suffixCode.charAt(jdx))) 
						{
							int kdx = 52 + ((int) suffixCode.charAt(jdx) - (int) '0');
							suffixCode = suffixCode.substring(0, jdx) + (char) codes[kdx + 1] + (char) codes[0];
						}
						else if (Character.isUpperCase(suffixCode.charAt(jdx))) 
						{
							int kdx = 26 + ((int) suffixCode.charAt(jdx) - (int) 'A');
							suffixCode = suffixCode.substring(0, jdx) + (char) codes[kdx + 1] + (char) codes[0];
						} 
						else 
						{
							int kdx = 0 + ((int) suffixCode.charAt(jdx) - (int) 'a');
							suffixCode = suffixCode.substring(0, jdx) + (char) codes[kdx + 1] + (char) codes[0];
						}
					} 
					else
					{
						int len = suffixCode.length();
						suffixCode = "";
						String ach = Character.toString((char) codes[0]);
						for (int l = 0; l < len + 1; l++)
						{
							suffixCode += ach;
						}
					}
						
				} 
				else
				{
					suffixCode = suffixCode.substring(0, suffixCode.length() - 1) + (char) codes[idx + 1];
				}
			} 
			else if (Character.isUpperCase(ch)) 
			{
				int idx = 26 + ((int) ch - (int) 'A');
				suffixCode = suffixCode.substring(0, suffixCode.length() - 1) + (char) codes[idx + 1];
			} 
			else 
			{
				int idx = 0 + ((int) ch - (int) 'a');
				suffixCode = suffixCode.substring(0, suffixCode.length() - 1) + (char) codes[idx + 1];
			}
		}
		
	}
}
